package de.szut.traineeslife.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;

import de.szut.traineeslife.taks.LoadDocumentsTask;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Files;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Toast;

public class FileHelper {
	private String directory = Environment.getExternalStorageDirectory().getAbsolutePath();
	private String traineesFolder = "mnt/sdcard/TraineesLife";
	private String traineesFolderModel = traineesFolder + "/Vorlage";
	private String traineesFolderReports = traineesFolder + "/Berichte";
	private String filePath = null;
	private String[] endings = { ".doc", ".odt", ".docx", ".pdf" };
	private ArrayList<String> isFile = new ArrayList<String>();
	private ArrayList<String> isDirectory = new ArrayList<String>();
	private File currentFile = null;

	public FileHelper() {
	}

	/**
	 * checks if the device has Sd-card mounted and if it is wirte- and readable
	 * 
	 * @param context
	 * @return
	 */
	public boolean isExternalStoragePresent(Context context) {

		boolean mExternalStorageAvailable = false;
		boolean mExternalStorageWriteable = false;
		String state = Environment.getExternalStorageState();

		if (Environment.MEDIA_MOUNTED.equals(state)) {
			// We can read and write the media
			mExternalStorageAvailable = mExternalStorageWriteable = true;
		} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
			// We can only read the media
			mExternalStorageAvailable = true;
			mExternalStorageWriteable = false;
		} else {
			mExternalStorageAvailable = mExternalStorageWriteable = false;
		}
		if (!((mExternalStorageAvailable) && (mExternalStorageWriteable))) {
			Toast.makeText(context, "SD card not present", Toast.LENGTH_LONG).show();

		}
		return (mExternalStorageAvailable) && (mExternalStorageWriteable);
	}

	/**Save Selected File to Sd Card
	 * @param directory
	 * @param fileToSave
	 * @return
	 */
	public boolean saveFileToExternalStorage(String directory, com.google.api.services.drive.model.File fileToSave) {

		try {
			File dir = new File(directory);
			if (!dir.exists()) {
				dir.mkdirs();
			}

			String fileName = fileToSave.getTitle();

			OutputStream fOut = null;
			File file = new File(directory, fileName);
			file.createNewFile();
			fOut = new FileOutputStream(file);

			fOut.flush();
			fOut.close();

			filePath = file.getAbsolutePath();

			return true;

		} catch (Exception e) {
			Log.e("saveToExternalStorage()", e.getMessage());
			return false;
		}
	}

	/**
	 * Loads Data from given directory path
	 * 
	 * @param dirPath
	 * @return
	 */
	public ArrayList<String> loadDirectory(String dirPath) {

		File directory = new File(dirPath);
		File[] filesInDirectory = directory.listFiles();

		for (int a = 0; a < filesInDirectory.length; a++) {
			currentFile = filesInDirectory[a];
			if (checkIfDocument(currentFile) == true) {
				isFile.add(currentFile.getPath());
			} else if (checkIfDirectory(currentFile) == true) {
				isDirectory.add(currentFile.getPath());
				for (int b = 0; b < isDirectory.size(); b++) {
					checkSubDir(isDirectory.get(b));
				}
			}
		}

		Log.d("ISFILE", Integer.toString(isFile.size()));
		return isFile;

	}

	/**
	 * checks for specific ending in files name
	 * 
	 * @param file
	 * @return
	 */
	public boolean checkIfDocument(File file) {
		for (String end : endings) {
			if (file.getName().toLowerCase().endsWith(end)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * checks if file is a directory
	 * 
	 * @param file
	 * @return
	 */
	public boolean checkIfDirectory(File file) {
		if (file.isDirectory() && file.listFiles() != null) {
			return true;
		}
		return false;

	}

	/**
	 * check given path for subdirectories
	 * 
	 * @param path
	 */
	public void checkSubDir(String path) {
		File f = new File(path);
		File[] list = f.listFiles();
		for (int i = 0; i < list.length; i++) {
			File file = list[i];
			if (checkIfDocument(file) == true) {
				isFile.add(file.getPath());
			} else if (checkDirForDoc(file) == true) {
				isDirectory.add(file.getPath());
			}
		}

	}

	/**
	 * Do the whole file oder directory check
	 * 
	 * @param file
	 * @return
	 */
	public boolean checkDirForDoc(File file) {
		if (checkIfDirectory(file) == true) {
			File[] fileList = file.listFiles();
			for (File file1 : fileList) {
				if (checkIfDocument(file1) == true) {
					return true;
				} else if (checkIfDirectory(file1) == true) {
					File[] subFiles = file1.listFiles();
					for (File subfile : subFiles) {
						if (checkIfDocument(subfile) == true) {
							return true;
						} else if (checkIfDirectory(subfile) == true) {
							File[] subSubFiles = subfile.listFiles();
							for (File subSubfile : subSubFiles) {
								if (checkIfDocument(subSubfile) == true) {
									return true;
								}
							}
						}
					}
				}
			}
		}
		return false;
	}
	
	/** Returns a list with the pathes from SdCard
	 * @return
	 */
	public ArrayList<File> getPathsFromSD(){
        File dir = new File( getDirectory() );
        File[] dirList = dir.listFiles();
//        final ArrayList<String> dirName = new ArrayList<String>();
//        final ArrayList<String> fileName = new ArrayList<String>();
        final ArrayList<File> listOfFile = new ArrayList<File>();
        for ( File file : dirList ) {
            if ( !file.getName().toLowerCase().startsWith( "." ) ) {
            	listOfFile.add(file);
//                dirName.add( file.getAbsolutePath() );
//                fileName.add( file.getName() );
            }
        }
//		return fileName;
        return listOfFile;
	}
	
	/** starts Background task to Load the Documents from SdCard
	 * @param context
	 * @param folderPath
	 * @param helper
	 * @param listener
	 */
	public void scanSdCardForFolders(Context context,String folderPath,FileHelper helper,DialogListener listener) {
	LoadDocumentsTask loadDocTask = new LoadDocumentsTask(context,folderPath, helper,listener);
	loadDocTask.execute();

}

	
	public String getDirectory() {
		return directory;
	}

	public String[] getEndings() {
		return endings;
	}

	public String getTraineesFolder() {
		return traineesFolder;
	}

	public String getTraineesFolderModel() {
		return traineesFolderModel;
	}

	public String getTraineesFolderReports() {
		return traineesFolderReports;
	}

	public String getFilePath() {
		return filePath;
	}

	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}
}
